//
//  ViewController.m
//  ObjectiveCallJavaScript
//
//  Created by JiaKang.Zhong on 03/12/2016.
//  Copyright © 2016 JiaKang.Zhong. All rights reserved.
//

#import "ViewController.h"
#import <WebKit/WebKit.h> // 使用WKwebview要导入此文件
#import <WKWebViewJavascriptBridge.h>
@interface ViewController ()<WKNavigationDelegate,WKNavigationDelegate>
@property (weak, nonatomic) IBOutlet UILabel *lblLog;
@property (weak, nonatomic) IBOutlet UIButton *buttonCallBack;
@property WKWebViewJavascriptBridge* bridge;
@end

@implementation ViewController
- (IBAction)ocCallJS:(id)sender {
    
    id data = @{@"data": @"oc调js啦"};
    [self.bridge callHandler:@"callJS" data:data responseCallback:^(id response) {
        NSLog(@"js返回了: %@", response);
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    WKWebView  *webView = [[WKWebView alloc] initWithFrame:self.view.frame];
    webView.backgroundColor = [UIColor clearColor];
    webView.userInteractionEnabled = YES;
    webView.navigationDelegate = self;
    [WKWebViewJavascriptBridge enableLogging];// 开启日志
    _bridge = [WKWebViewJavascriptBridge bridgeForWebView:webView];
    [_bridge setWebViewDelegate:self];
    [_bridge registerHandler:@"getJson" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"JS called Objective,objectie get js param: %@", data);
        NSDictionary * returnData = @{@"data":@"objective return js param is hello world"};
        responseCallback(returnData);
    }];
    [_bridge registerHandler:@"Login" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"JS called Objective,objectie get js param: %@", data);
        // 写登录逻辑判断
        NSDictionary * returnData = @{@"data":@"登录成功"};
        responseCallback(returnData);
    }];
    NSString * htmlFile =  [[NSBundle mainBundle] pathForResource:@"test.html" ofType:nil];
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:htmlFile]]];// 注意html文件的路径
    [self.view addSubview:webView];
   
    
    [self.view bringSubviewToFront:self.lblLog];
    [self.view bringSubviewToFront:self.buttonCallBack];
}

@end
